<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId" :isPropagation="isPropagation">
    <template v-slot:common>
      <canvas v-if="commonAttr.isSvga" ref="svg" class="wb-svg-icon" :style="styles"></canvas>
      <div v-else ref="svg" class="wb-svg-icon" :style="styles"></div>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { getPxOVwByValue } from '@/store/utils'
import { EventBus } from '@/store/index'

export default {
  name: 'WbSvgIcon',
  mixins: [utils, commonUtils],
  components: {
    InjectTemplate
  },
  setup(){
    return{
      isPropagation: false
    }
  },
  created() {
    if(!this.isH5Edit) {
      if(this.commonAttr.isSvga) {
        this.isPropagation = false;
        if(!window.SVGA){
          this.dynamicsLoadScript(this.env.baseUrl + "js/svg/svga.min.js", "SVGA", this.initSvga);
        }
      } else {
        if(!window.Vivus){
          this.dynamicsLoadScript(this.env.baseUrl + "js/svg/vivus.min.js", "Vivus", this.initVivus)
        }
        this.progress = 0;
        EventBus.$off("svgPathAnimate", this.onPlayPathAnimate);
        EventBus.$on("svgPathAnimate", this.onPlayPathAnimate);
        EventBus.$off("resetVivus", this.resetVivus);
        EventBus.$on("resetVivus", this.resetVivus);
        EventBus.$off("setVivusProress", this.setVivusProress);
        EventBus.$on("setVivusProress", this.setVivusProress);
        if(this.commonAttr.isDrag) {
          this.isPropagation = false;
        } else {
          this.isPropagation = true;
        }
      }
    }
  },
  mounted() {
    if(this.commonAttr.isSvga) {
      this.initSvga(window.SVGA);
    } else {
      this.initVivus(window.Vivus);
    }
  },
  methods: {
     async initSvga(SVGA) {
      if(!SVGA || !this.$refs.svg){
        return
      }
      const parser = new window.SVGA.Parser();
      const svga = await parser.load(this.commonAttr.svgaUrl);
      const player = new window.SVGA.Player(this.$refs.svg);
      await player.mount(svga);

      player.start();
      this.parser = parser;
      this.player = player;
    },
    initVivus(Vivus){
      if(!Vivus || !this.$refs.svg){
        return
      }

      if(this.vivus){
        this.vivus.stop().destroy();
      }
      if(this.$refs.svg) this.$refs.svg.innerHTML = '';
      // this.commonAttr.start = "inViewport";
      //play(speed, callback) stop() reset() finish() setFrameProgress(progress) getStatus() destroy()
      let strokeWidth = this.commonAttr.strokeWidth + 'px';
      let commonAttr = this.commonAttr;
      let strokeColor = this.item.styles.color;
      this.vivus = new Vivus(this.$refs.svg, {
        duration: commonAttr.duration,
        file: commonAttr.url,
        type: commonAttr.type,//delayed, sync, oneByOne, script, scenario or scenario-sync
        start: commonAttr.start,//inViewport manual autostart
        delay: commonAttr.delay,
        pathTimingFunction: Vivus[commonAttr.pathTimingFunction],//LINEAR EASE EASE_OUT EASE_IN EASE_OUT_BOUNCE
        animTimingFunction: Vivus[commonAttr.animTimingFunction],
        dashGap: commonAttr.dashGap,
        forceRender: true,
        reverseStack: commonAttr.reverseStack,
        selfDestroy: true,
        onReady: function (vivus) {
          // vivus.el.setAttribute('height', 'auto');
          const path = vivus.el.getElementsByTagName('path')[0]
          path.style['stroke-width'] = strokeWidth
          path.style['stroke'] = strokeColor
          vivus.el.style.setProperty(`--stroke-width`, strokeWidth);
          vivus.el.style.setProperty(`--stroke-color`, strokeColor);
          if(commonAttr.start != "inViewport"){
            vivus.stop();
          }
        }
      }, () => {
        console.log("动画播放完成！")
      });

    },
    onPlayPathAnimate(){
      if(this.vivus){
        this.vivus.reset();
        this.vivus.play();
      }
      //svgAnimateIndex
      // http://lmgonzalves.github.io/segment/
      // const aimatePencents = this.commonAttr.animatePercents.split(',');
      // if(aimatePencents[svgAnimateIndex]){
      //   const percent = aimatePencents[svgAnimateIndex];
      //   const svgCon = this.$refs.svg;
      //   const svgPath = svgCon.getElementsByTagName('path')[0];
      //   const segment = new window.Segment(svgPath);
      //   segment.draw("0", percent, 5, {easing: window.d3['easeCubicOut']});
      // }
    },
    resetVivus() {
      if(this.vivus) this.vivus.reset();
    },
    setVivusProress(progress) {
      if(this.vivus && progress > this.progress) this.vivus.setFrameProgress(progress);
      this.progress = progress;
    },
    onRefreshCommonAttr() {
      this.initVivus(window.Vivus);
    },
  },
  beforeUnmount() {
    if(this.isH5Edit) {
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
    }
    EventBus.$off("svgPathAnimate", this.onPlayPathAnimate);
    EventBus.$off("resetVivus", this.resetVivus);
    EventBus.$off("setVivusProress", this.setVivusProress);

    if(this.vivus) {
      this.vivus.destroy();
      this.vivus = null;
    }
    if(this.parser) {
      this.parser.destroy()
      this.player.destroy()
    }
  }
};
</script>
<style lang="scss" scoped>
.wb-svg-icon {
  --stroke-width: var(--size-36);
  --stroke-color: #f98747;
  width: inherit;
  height: inherit;
  display: flex;
  justify-content: center;
  align-items: center;
}
svg {
  width: 100%;
  stroke-width: var(--stroke-width);
  stroke-linecap: round;
  stroke-linejoin: round;
  fill-rule: evenodd;
}
svg * {
  fill: none;
  stroke: var(--stroke-color);
}
</style>
